#include "Log.hpp"
#include <string>
#include <sys/types.h>          
#include <sys/socket.h>
#include <cstring>
#include <netinet/in.h>
#include <strings.h>
#include <arpa/inet.h>
#include <functional>


typedef function<std::string(const std::string&)> func_t;

const int size = 1024;
std::string defaultip = "0.0.0.0";
uint16_t defaultport = 8080;

Log log;

enum
{
    SOCKET_ERR = 1,
    BIND_ERR
};

class UdpServer
{
public:
    UdpServer(const uint16_t& port = defaultport)
        : _sockfd(0)
        , _ip(defaultip)
        , _port(port)
    {}

    void Init()
    {
        // 创建udp socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            log(Fatal, "socket create error, errno: %d, err string: %s", errno, strerror(errno));
            exit(SOCKET_ERR);
        }

        // bind socket
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        // local.sin_addr.s_addr = htonl(INADDR_ANY);

        if(bind(_sockfd, (const struct sockaddr*)&local, sizeof(local)) < 0)
        {
            log(Fatal, "bind error, errno: %d, err string: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
    }

    void Run(func_t func)
    {
        char inbuffer[size];
        
        while(true)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr*)&client, &len);
            if(n < 0)
            {
                log(Warning, "recvfrom error, errno: %d, err string: %s", errno, strerror(errno));
                continue;
            }
            inbuffer[n] = 0;
            std::string info = inbuffer;
            std::string echo_string = func(info);
            sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, (const struct sockaddr*)&client, len);
        }
    }

    ~UdpServer()
    {}

private:
    int _sockfd;            // 网络文件描述符
    std::string _ip;        // 任意地址 bind 0
    uint16_t _port;         // 表明服务器进程的端口号
};